<template>
  <div class="tpl-container">
    <div class="mb20 condition-container">
      <div class="condition">
        <span class="w70 color_494949 ft12 pr5">{{ translate('物料编码') }}：</span>
        <ElInput
          v-model="itemcode"
          class="w164 mr14"
          :placeholder="translate('请输入物料名称')"
        />
      </div>
      <div class="condition">
        <span class="w70 color_494949 ft12 pr5">{{ translate('库位') }}：</span>
        <ElInput
          v-model="wsCode1"
          class="w164 mr14"
          :placeholder="translate('请输入库位')"
        />
      </div>
      <div class="condition">
        <span class="w70 color_494949 ft12 pr5">{{ translate('仓库单位') }}：</span>
        <el-autocomplete
          v-model="whUnit"
          class="inline-input mr10 w164"
          :fetch-suggestions="querySearch"
          placeholder="选择单位"
          @select="handleSelect"
        />
      </div>
      <div class="condition">
        <span class="w70 color_494949 ft12 pr5">{{ translate('存放地点') }}：</span>
        <ElInput
          v-model="storageLocation"
          class="w164 mr14"
          :placeholder="translate('请输入存放地点')"
        />
      </div>
      <div class="condition">
        <span class="w70 color_494949 ft12 pr5">{{ translate('发料单号') }}：</span>
        <ElInput
          v-model="FLCode"
          class="w164 mr14"
          :placeholder="translate('请输入发料单号')"
        />
      </div>
      <div class="condition">
        <span class="w70 color_494949 ft12 pr5">{{ translate('批次号') }}：</span>
        <ElInput
          v-model="batchNo"
          class="w164 mr14"
          :placeholder="translate('请输入批次号')"
        />
      </div>
      <div class="condition">
        <span class="w70 color_494949 ft12 pr5">{{ translate('审核时间') }}：</span>
        <el-date-picker
          v-model="dateTime"
          end-placeholder="结束日期"
          range-separator="至"
          start-placeholder="开始日期"
          type="daterange"
          value-format="YYYY-MM-DD"
        />
        <ElButton class="settingBtn ml10" type="primary" @click="search">
          {{ translate('查询') }}
        </ElButton>
        <ElButton class="settingBtn" type="primary" @click="resetFn">
          {{ translate('重置') }}
        </ElButton>
      </div>
    </div>
    <div class="add">
        <ElButton class="settingBtn" type="primary" @click="exportFn" plain>
          {{ translate('导出') }}
        </ElButton>
    </div>
    <div class="table">
      <ElTable
        ref="multipleTableRef"
        v-loading="loading"
        :border="true"
        :data="tableData"
      >
        <ElTableColumn
          :label="translate('序号')"
          type="index"
          width="auto"
        />
        <ElTableColumn :label="translate('批次号')" width="150">
          <template #default="{ row }">
            <div>
              <span class="iconcolor">{{ row.BatchNo }}</span>
              <vab-icon  v-if="row.BatchNo" icon="file-copy-line" @click="copyToClipboard(row.BatchNo)" />
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn :label="translate('物料编码')" prop="ItemCode" width="150">
          <template #default="{ row }">
            <div>
              <span class="iconcolor">{{ row.ItemCode }}</span>
              <vab-icon icon="file-copy-line" @click="copyToClipboard(row.ItemCode)" />
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn
          :label="translate('四号定位')"
          prop="WSCode"
          width="auto"
        />
        <ElTableColumn :label="translate('物资名称/规格')" width="150">
          <template #default="{ row }">
            <div>
              <span>{{ row.ItemName }}</span>
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn :label="translate('计量单位')" prop="ItemUnit" width="auto" />
        <ElTableColumn :label="translate('大类')" width="60">
          <template #default="{ row }">
            <div>
              <span>{{ row.ItemCate }}</span>
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn :label="translate('发出数量')" width="auto">
          <template #default="{ row }">
            <div>
              <span>{{ row.Qty }}</span>
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn :label="translate('单价')" width="auto">
          <template #default="{ row }">
            <div>
              <span class="color_red">{{ row.Price }}</span>
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn :label="translate('发出合计金额')" width="auto">
          <template #default="{ row }">
            <div>
              <span class="color_red">{{ row.ItemAmt }}</span>
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn
          :label="translate('领料单位')"
          prop="POUnit"
          width="auto"
        />
        <ElTableColumn
          :label="translate('领料时间')"
          prop="LLDate"
          width="auto"
        />
        <ElTableColumn :label="translate('备注')" prop="Remark" sortable width="auto"  show-overflow-tooltip/>
        <ElTableColumn
          :label="translate('井号')"
          prop="Oilwell"
          width="auto"
        />
        <ElTableColumn
          :label="translate('作业内容')"
          prop="WorkContent"
          width="auto"
        />
        <ElTableColumn :label="translate('发料单号')" prop="ItemCode" width="150">
          <template #default="{ row }">
            <div>
              <span class="iconcolor">{{ row.Code }}</span>
              <vab-icon icon="file-copy-line" @click="copyToClipboard(row.Code)" />
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn
          :label="translate('存放地点')"
          prop="StorageLocation"
          width="auto"
        />
        <!-- <ElTableColumn align="center" :label="translate('操作')" width="100">
          <template #default="{ row }">
            <div>
              <ElButton plain size="small" type="danger" @click="deleteFn(row)">
                {{ translate('删除') }}
              </ElButton>
            </div>
          </template>
        </ElTableColumn> -->
      </ElTable>
      <div v-if="total > 0" class="pagination">
        <ElPagination
          background
          :current-page="searchInfo.pageNo"
          :layout="layout"
          :page-size="searchInfo.pageSize"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>
    <el-dialog
      v-model="dialogVisible"
      :title="translate('修改库存数量')"
      width="400px"
      @close="closeFn"
    >
      <div>
        <span class="w70 color_494949 ft12 pr5">{{ translate('库存数量') }}：</span>
        <ElInput
          type="number"
          v-model="sotckQty"
          class="w164 mr14"
          :placeholder="translate('请输入库存数量')"
        />
      </div>
      <template #footer>
        <el-button @click="dialogVisible = false">
          {{ translate('取消') }}
        </el-button>
        <el-button type="primary" @click="submit">
          {{ translate('确定') }}
        </el-button>
      </template>
    </el-dialog>
    <el-dialog
      v-model="dialogChiled"
      :title="translate('出库物资用途井号明细')"
      width="800px"
    >
      <div>
        <div class="ITtitle">
          <span>物料编码:</span>
          <span>{{itemID}}</span>
        </div>
        <el-table
          border
          :data="tableData1"
          height="400"
          style="width: 800px"
        >
          <el-table-column :label="translate('仓库单位')" prop="whUnit" />
          <el-table-column :label="translate('库位')" prop="wsCode" />
          <el-table-column :label="translate('井上')" prop="wellNumber" />
          <el-table-column :label="translate('备注')" prop="remark" />
          <el-table-column :label="translate('数量')" prop="qty" />
        </el-table>
      </div>
      <template #footer>
        <el-button @click="dialogChiled = false">
          {{ translate('取消') }}
        </el-button>
        <!-- <el-button type="primary" @click="submitChiled()">
          {{ translate('确定') }}
        </el-button> -->
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
  import { ref } from 'vue'
  import {
    GetPageDataOutBillAudit,
    Wms_ItemStockDown,
    ExportOutBillAudit,
    delInOuStock,
    correctsave,
    getpickdinfolist,
  } from '@/api/mupro'
  import { BaseGetPageData, savestock } from '@/api/item'
  import { MenuAuth } from '~/src/utils/permission'
  import { useUserStore } from '@/store/modules/user'
  import { translate } from '@/i18n'
  import { baseURL } from '@/config'
  import { parseTime } from '@/utils'
  const { token } = useUserStore()
  const userStore = useUserStore()
  const { realname } = storeToRefs(userStore)
  const searchInfo2 = ref('')
  const itemcode = ref('')
  const whUnit = ref('')
  const wsCode1 = ref('')
  const storageLocation = ref('')
  const date = ref('')
  const jsvalue = ref('')
  const dialogVisible = ref(false)
  const FLCode = ref('')
  const batchNo = ref('')
  const searchInfo = reactive({
    pageNo: 1,
    pageSize: 10,
    tableName: '',
    sort: '',
    order: '',
    wheres: `[ {"name":"ItemCode","value":${itemcode.value},"displayType":"like"},
              {"name":"WHUnit","value":${whUnit.value},"displayType":"like"},
              {"name":"StorageLocation","value":${storageLocation.value},"displayType":"like"},
              {"name":"Code","value":${FLCode.value},"displayType":"like"},
              {"name":"BatchNo","value":${batchNo.value},"displayType":"like"},
              {"name":"WSCode","value":${wsCode1.value},"displayType":"like"}]`,
    export: false,
    value: '',
  })
  const getLastDayOfMonth = ()=> {
      // 创建一个当前日期的副本
          let date = new Date();

          // 设置日期为下个月的第一天（这样可以跳过本月所有日期）
          date.setDate(1);
          date.setMonth(date.getMonth() + 1);
          date.setDate(0); // 这会将日期设置为上一个月的最后一天

          // 格式化日期为 YYYY-MM-DD
          let year = date.getFullYear();
          let month = String(date.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的，所以要加1
          let day = String(date.getDate()).padStart(2, '0');

          return `${year}-${month}-${day}`;
      }
     const getFirstDayOfMonthFormatted = () => {
            const today = new Date(); // 获取当前日期
            const year = today.getFullYear(); // 获取年份
            const month = today.getMonth(); // 获取月份（注意：0表示1月，11表示12月）
            const date = 1; // 设置日期为1（即当前月份的第一天）

            // 创建日期对象
            const firstDay = new Date(year, month, date);

            // 手动格式化日期为 YYYY-MM-DD
            const formattedDate = `${year.toString().padStart(4, '0')}-${(month + 1).toString().padStart(2, '0')}-${date.toString().padStart(2, '0')}`;
            return formattedDate;
        }
  const dateTime = ref([getFirstDayOfMonthFormatted(),getLastDayOfMonth()])
  const loading = ref(false)
  const action = ref('')
  const layout = ref('total, sizes, prev, pager, next, jumper')
  const tableData = ref([])
  const total = ref(0)
  const listLoading = ref(false)
  const headers = ref('')
  const WHdata = ref([])
  const selectInfo = ref('')
  const sotckQty = ref('')
  const tableData1 = ref([])
  const dialogChiled = ref(false)
  const itemID = ref('')
  // 获取表格数据
  const gettableData = async () => {
    const searcharr = []
    if (sessionStorage.getItem('itemcode')) {
      itemcode.value = sessionStorage.getItem('itemcode')
      searcharr.push({
        name: 'ItemCode',
        value: sessionStorage.getItem('itemcode'),
        displayType: 'like',
      })
    }
    if (sessionStorage.getItem('whUnit')) {
      whUnit.value = sessionStorage.getItem('whUnit')
      searcharr.push({
        name: 'WHUnit',
        value: sessionStorage.getItem('whUnit'),
        displayType: 'like',
      })
    }
    if (sessionStorage.getItem('FLCode')) {
      FLCode.value = sessionStorage.getItem('FLCode')
      searcharr.push({
        name: 'Code',
        value: sessionStorage.getItem('FLCode'),
        displayType: 'like',
      })
    }
    if (sessionStorage.getItem('FLbatchNo')|| batchNo.value) {
      batchNo.value = sessionStorage.getItem('FLbatchNo') || batchNo.value
      searcharr.push({
        name: 'BatchNo',
        value: sessionStorage.getItem('FLbatchNo') || batchNo.value,
        displayType: 'like',
      })
    }
    if(sessionStorage.getItem('wsCode1')) {
      wsCode1.value = sessionStorage.getItem('wsCode1')
      searcharr.push({
        name: 'WSCode',
        value: sessionStorage.getItem('wsCode1'),
        displayType: 'like',
      })
    }
    if(sessionStorage.getItem('storageLocation')) {
      storageLocation.value = sessionStorage.getItem('storageLocation')
      searcharr.push({
        name: 'StorageLocation',
        value: sessionStorage.getItem('storageLocation'),
        displayType: 'like',
      })
    }
    if(sessionStorage.getItem('dateTime')|| dateTime.value){
      dateTime.value  = JSON.parse(sessionStorage.getItem('dateTime')) ||  dateTime.value
      console.log(dateTime.value)
      if(dateTime.value.length>0){
        console.log(dateTime.value)
        searcharr.push({
            name: 'ModifyDate',
            value: dateTime.value[0],
            displayType: 'ThanOrEqual',
        })
        searcharr.push({
          name: 'ModifyDate',
          value: dateTime.value[1],
          displayType: 'LessOrequal',
        })
      }
    }
    console.log( wsCode1.value)
    searchInfo.wheres = JSON.stringify(searcharr)
    loading.value = true
    const { data } = await GetPageDataOutBillAudit(searchInfo)
    loading.value = false
    tableData.value = data?.rows || []
    total.value = data?.total || 0
  }
  gettableData()
  // 重置
  const resetFn = () => {
    itemcode.value = ''
    whUnit.value = ''
    wsCode1.value = ''
    dateTime.value = []
    storageLocation.value = ''
    batchNo.value = ''
    sessionStorage.removeItem('itemcode')
    sessionStorage.removeItem('whUnit')
    sessionStorage.removeItem('wsCode1')
    sessionStorage.removeItem('dateTime')
    sessionStorage.removeItem('storageLocation')
    sessionStorage.removeItem('FLCode')
    sessionStorage.removeItem('FLbatchNo')

    gettableData()
  }
  const getpickdinfolists = async (val: any) => {
        const params = {
          formId: val.BillNo,
          itemCode: val.ItemCode
        }

        const data  = await getpickdinfolist(params)
        if(data.code === '200') {
          tableData1.value = data.data.data
          dialogChiled.value = true
        }
  }
  // const Inquire = (val: any) => {
  //   itemID.value = val.ItemCode
  //   getpickdinfolists(val)
  // }
  //  修改库存数量
  const exitStockQty = (val: any) => {
        selectInfo.value = val.IOId
        dialogVisible.value = true
  }
  const closeFn = () => {
    dialogVisible.value = false
  }
  const submit = async () => {
      const params = {
         ioId: selectInfo.value,
         stockQty: sotckQty.value
      }
      const data = await correctsave(params)
      if(data.code === '200') {
          ElMessage({
            message: '保存成功',
            type: 'success',
          })
          dialogVisible.value = false
          gettableData()
      }else {
        ElMessage({
          message: data.message,
          type: 'error',
        })
      }
  }
  //分页条数切换
  const handleSizeChange = (val: any) => {
    searchInfo.pageSize = val
    gettableData()
  }
  const $baseConfirm = inject('$baseConfirm') as any
  const deleteFn = (row: any) => {
    $baseConfirm(translate('你确定要删除当前项吗'), null, async () => {
      const data = await delInOuStock({
        ioId: row.IOId,
      })
      if (data.code === '200') {
        ElMessage({
          message: data.message,
          type: 'success',
        })
      }
      gettableData()
    })
  }
  // 导出
  const exportFn = async () => {
    // params.pageNo = 1
    const searcharr = []

    if (itemcode.value != '') {
      searcharr.push({
        name: 'ItemCode',
        value: itemcode.value,
        displayType: 'like',
      })
    }
    if (whUnit.value != '') {
      searcharr.push({
        name: 'WHUnit',
        value: whUnit.value,
        displayType: 'like',
      })
    }
    if (FLCode.value != '') {
      searcharr.push({
        name: 'Code',
        value: FLCode.value,
        displayType: 'like',
      })
    }
    if(wsCode1.value != '') {
      searcharr.push({
        name: 'WSCode',
        value: wsCode1.value,
        displayType: 'like',
      })
    }
    if(storageLocation.value != '') {
      searcharr.push({
        name: 'StorageLocation',
        value: storageLocation.value,
        displayType: 'like',
      })
    }
    if(batchNo.value != '') {
      searcharr.push({
        name: 'BatchNo',
        value: batchNo.value,
        displayType: 'like',
      })
    }
   if(dateTime.value && dateTime.value.length>0){
      searcharr.push({
          name: 'ModifyDate',
          value: dateTime.value[0],
          displayType: 'ThanOrEqual',
        })
      searcharr.push({
          name: 'ModifyDate',
          value: dateTime.value[1],
          displayType: 'LessOrequal',
        })
   }
    searchInfo.wheres = JSON.stringify(searcharr)
    const data = await ExportOutBillAudit(searchInfo)
    const time = parseTime(new Date().getTime(), '{y}{m}{d}{h}{i}{s}')
    const blob = new Blob([data])
    const url = URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.download = `物资发料台账${time}.xlsx`
    link.href = url
    link.click()
  }
  //分页切换
  const handleCurrentChange = (val: any) => {
    searchInfo.pageNo = val
    gettableData()
  }
  const handleSelect = (item) => {
    console.log(item)
  }
  //复制彩屏标识
 const copyToClipboard =async (val: any) => {
    if (navigator.clipboard && window.isSecureContext) {
      try {
      console.log(navigator.clipboard)
      console.log(window.isSecureContext)
      await navigator.clipboard.writeText(val)
      ElMessage({
        message:'复制成功',
        type:'success',
      })
      } catch (err) {
        ElMessage({
        message:'复制失败',
        type:'error',
      })
      }

    }else {
      // 创建text area
    const textArea = document.createElement("textarea")
    textArea.value = val
    // 使text area不在viewport，同时设置不可见
    textArea.style.position = "absolute"
    textArea.style.opacity = 0
    textArea.style.left = "-999999px"
    textArea.style.top = "-999999px"
    document.body.appendChild(textArea)
    textArea.focus()
    textArea.select()

    return new Promise((res, rej) => {
      // 执行复制命令并移除文本框
      document.execCommand("copy") ? res() : rej()
      textArea.remove()
    }).then(() => {
         ElMessage({
          message: "复制成功",
          type: "success",
        })
      }).catch((err) => {
        ElMessage({
          message: "复制失败",
          type: "error",
        })
      })
    }

  }
  const querySearch = (queryString, cb) => {
    const restaurants = WHdata.value
    const results =
      queryString && queryString != 'null'
        ? restaurants.filter(createFilter(queryString))
        : restaurants
    console.log(results)
    // 调用 callback 返回建议列表的数据
    cb(results)
  }
  const createFilter = (queryString) => {
    return (restaurant) => {
      console.log(restaurant)
      return (
        restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
      )
    }
  }
  const WHGetPageData1 = async () => {
    const params = {
      pageNo: 1,
      pageSize: 10,
      wheres: `[{"name":"ModuleId","value":"","displayType":"equal"}]`,
      export: true,
      moduleType: 'ModuleId',
      sort: 'SortCode',
      order: 'ASC',
      search: '',
    }
    const data = await BaseGetPageData(params)
    if (data.data.rows && data.data.rows.length > 0) {
      data.data.rows.map((item) => {
        item.value = item.FullName
      })
    }
    WHdata.value = data.data.rows
  }
  WHGetPageData1()
  const search = () => {
    searchInfo.pageNo = 1
    if (
      itemcode.value.trim() !== '' ||
      whUnit.value.trim() !== '' ||
      wsCode1.value.trim() !== ''||
      storageLocation.value.trim() !== ''||
      FLCode.value.trim() !== ''||
      batchNo.value.trim() !== ''||
      (dateTime.value && dateTime.value.length > 0)
    ) {
      const arr = []
      itemcode.value.trim() !== '' &&
        arr.push({
          name: 'ItemCode',
          value: itemcode.value,
          displayType: 'like',
        })
      whUnit.value.trim() !== '' &&
        arr.push({
          name: 'WHUnit',
          value: whUnit.value,
          displayType: 'like',
        })
        wsCode1.value.trim() !== '' &&
        arr.push({
          name: 'WSCode',
          value: wsCode1.value,
          displayType: 'like',
        })
        FLCode.value.trim() !== '' &&
        arr.push({
          name: 'Code',
          value: FLCode.value,
          displayType: 'like',
        })
        batchNo.value.trim() !== '' &&
        arr.push({
          name: 'BatchNo',
          value: batchNo.value,
          displayType: 'like',
        })
        storageLocation.value.trim() !== '' &&
        arr.push({
          name: 'StorageLocation',
          value: storageLocation.value,
          displayType: 'like',
        })
        dateTime.value && dateTime.value.length>0 &&
        dateTime.value[0].trim() !== '' &&
        arr.push({
          name: 'ModifyDate',
          value: dateTime.value[0],
          displayType: 'ThanOrEqual',
        })
      dateTime.value && dateTime.value.length>0 &&
        dateTime.value[1].trim() !== '' &&
        arr.push({
          name: 'ModifyDate',
          value: dateTime.value[1],
          displayType: 'LessOrequal',
        })
      searchInfo.value = jsvalue.value
      searchInfo.wheres = JSON.stringify(arr)
    } else {
      searchInfo.value = ''
      searchInfo.wheres = `[{"name":"ItemCode","value": '',"displayType":"like"}]`
    }
    if(dateTime.value && dateTime.value != null && dateTime.value!='null') {
        sessionStorage.setItem('dateTime', JSON.stringify(dateTime.value))
      }else{
        sessionStorage.setItem('dateTime', JSON.stringify([]))
      }
      sessionStorage.setItem('itemcode', itemcode.value)
      sessionStorage.setItem('wsCode1', wsCode1.value)
      sessionStorage.setItem('whUnit', whUnit.value)
      sessionStorage.setItem('FLCode', FLCode.value)
      sessionStorage.setItem('FLbatchNo', FLCode.value)
      sessionStorage.setItem('storageLocation', storageLocation.value)
    // searchInfo.date = date.value
    console.log(wsCode1.value)
    gettableData()
  }
</script>

<style lang="scss" scoped>
  .tpl-container {
    .color_494949 {
      color: #494949;
    }

    .noData {
      text-align: center;
      font-size: 16px;
      color: gray;
    }
    .w164 {
      width: 164px !important;
    }
    .inline-input {
      width: 164px !important;
    }
    .mb20 {
      margin-bottom: 20px;
    }

    .img-container {
      display: flex;
      // justify-content: center;

      .img {
        width: 100px;
      }
    }
    .w70 {
      display: inline-block;
      width: 70px;
      text-align: right;
    }

    .condition-container {
      display: flex;
      flex-wrap: wrap;
      align-items: center;

      .condition {
        margin-right: 14px;
        margin-bottom: 10px;
      }
    }
  }
  .el-table {
    & ::v-deep th.el-table__cell,
    ::v-deep td.el-table__cell {
      // 设置position 使得 子元素不与其产生新的层叠关系
      position: static;
    }
  }
  ::v-deep .el-autocomplete {
    width: 164px;
  }
  .ml-upload {
    display: inline-block;
    margin-left: 10px;
    vertical-align: bottom;
    margin-right: 10px;
  }
  .add {
      margin-bottom: 10px;
      text-align: left;
    }
  .iconcolor {
      color: #409eff;
    }
  .color_l {
      color: #67c23a;
    }
  .color_red {
      color: #f56c6c;
    }
  .ITtitle {
    text-align: center;
    padding: 10px;
    box-sizing: border-box;
    font-size: 18px;
    font-weight: 600;
  }
  .ml10 {
    margin-left: 10px;
  }
</style>
